define(['moment','module/system/service/WatchDogService'], function (moment) {
    return ['$scope', '$rootScope' ,'$filter', '$stateParams', '$timeout', 'config', 'MMWService', 'WatchDogService', 'RouterExtendProvider',
    function ($scope, $rootScope ,$filter, $stateParams, $timeout, config, $MMWService, $WatchDogService, $RouterExtendProvider) {
        var dog = {
            bark:function(feed, next){
                $scope.search(next);
            }
        };

        $scope.init = function(){
            $RouterExtendProvider.AddEventListener($scope,
                'ServicesSTD.Module_SYS.print_queue_send_process',
            function(data){
                $scope.receive_time = moment().format('YYYY-MM-DD HH:mm:ss');
                if(!$scope.itemList.find(function(item){
                    return item.guid == data.guid;
                })){
                    $scope._itemList.push(data);
                    itemClick(data);
                }
            });
            $scope.printer_no = config.cache.account;
			$scope.filterItem = {};
            $scope.itemList = [];
            $scope._itemList = [];
            $scope.itemLogList = [];
			$scope.filterItem = {};
			$scope.filterItemSH = {};
			$scope.PageConfig = {page : 0, page_count : 25};
            $WatchDogService.startWatch(dog, false);
        };

        $scope.back = function(){
            $scope.$root.hideMenu();
            $scope.$root.changeProgram('home', true);
        };

        $scope.final = function(callback){
            $WatchDogService.stopWatch();
            if(typeof callback === 'function')
                callback();
        }

        $scope.search = function(next){
			var content = {
                print_target:$scope.printer_no
            };
            $MMWService.sendToServer({
                uri: 'ServicesSTD.Module_SYS.print_queue_info_get',
                content : content,
                success : function(data){
                    try{
                        $scope.refresh_time = moment().format('YYYY-MM-DD HH:mm:ss');
                        $scope.itemList = data.print_queue_list;
                        $scope.itemList.forEach(function(item){
                            if($scope._itemList.find(function(_item){
                                return _item.guid == item.guid;
                            })){
                                item.hide = 'true';
                            } else {
                                itemClick(item);
                            }
                        });

                        $scope.itemLogList = data.print_queue_log_list;
                    }catch (e) {
                        console.error(e);
                    }
                    if(next)
                        next();
                }
            }, next == undefined);
        };

        $scope.itemCheck = function(index, item, print_type){
			$scope.$root.showConfirm($filter('translate')('RemotePrint.msg.reprint'), function(confirmDialog){
                confirmDialog.hide();
                itemClick(item, print_type);
			});
        };

        function itemClick(item, print_type){
            var _commandline = JSON.parse(item.print_json),
                _print_success = function(status){
                    PrintQueueUpdateProcess({
                        guid : item.guid,
                        status:status
                    });
                    if(print_type!= 'log'){
                        item.hide = 'true';
                    }

                    //$scope.search();
                };
            if(item.print_type == 0){
                printLabelWin(item, _commandline, _print_success);
            } else if(item.print_type == 1){
                printLabelBartender(item, 0, _commandline, _print_success);
            }
        }

        //分頁
        $scope.getPages = function(list, PageConfig, filterItem){
            if(list){
               var temp_list = list.filter(function(item, index, array){
                    var isOK = true,
                        keys = Object.keys(filterItem);
                    for(var i =0; i<keys.length;i++){
                        var key = keys[i];
                        if(isOK && item[key]!=null && filterItem[key] && filterItem[key]!=''){
                            if(item[key].toString().indexOf(filterItem[key]) == -1){
                                isOK = false;
                                break;
                            }
                        }
                    }
                    return isOK;
                });
                if(PageConfig){
                    if(temp_list.length != 0){
                        PageConfig.total_page = Math.ceil(temp_list.length/PageConfig.page_count);

                        if(PageConfig.page >= PageConfig.total_page){
                            PageConfig.page = 0;
                        }
                        var index = PageConfig.page*PageConfig.page_count;
                        return temp_list.slice(index, index+PageConfig.page_count);
                    } else {
                        PageConfig.total_page = 1;
                        PageConfig.page = 0;
                    }
                } else {
                    return temp_list;
                }
            } else {

                return list;
            }
        };

        function PrintQueueUpdateProcess(content){
            var sendData = {
                uri : 'ServicesSTD.Module_SYS.print_queue_update_process',
                content : content
            };
            $RouterExtendProvider.NotificationHub.invoke('InvokeJSON', {
                header:$MMWService.prepareHeader(sendData),
                content:$MMWService.prepareContent(sendData)
            });
        }

		//Bartender
		function printLabelBartender(item, index, pcsno_detail, success){
            if(pcsno_detail && index < pcsno_detail.length){
                if(window.nodeRequire){
                    var exec = window.nodeRequire('child_process').exec;
                    exec(pcsno_detail[index].commandline, function(error, stdout, stderr){
                        if(error){
                            console.error(error);
                            $scope.$root.showToast($filter('translate')('E01.msg.cantprint'));
                        }
                        index = index +1;
                        printLabelBartender(item, index, pcsno_detail, success);
                    });
                }
            } else {
                success(1);
            }
        }

		//ActiveReport
        function printLabelWin(item, data, success){
            var timeInMs = Date.now();
            if(config.setting.outsidePDF == 'Y'){
                var fs = window.nodeRequire('fs'), RuncardPath;
                try{
                    RuncardPath = window.nodeRequire('electron').remote.app.getAppPath();
                }catch(e){
                    RuncardPath = window.nodeRequire('path').dirname(process.execPath)+'\\package.nw';
                }
                RuncardPath += '\\www\\Runcard';
                if(!fs.existsSync(RuncardPath)){
                    fs.mkdirSync(RuncardPath);
                }
                $rootScope.downloadFile(data.file_path, RuncardPath+'\\RuncardPreview'+timeInMs+'.pdf', function(dist_path){
                    //window.nodeRequire('electron').shell.openItem(dist_path);
                    window.nodeRequire('child_process').exec('@powershell "start -verb print ""'+dist_path+'"""', (err, stdout, stderr) => {
                        var _status = 1;
                        if (err) {
                            // 20240223 modify by Alan for#158194 : 優化錯誤提示
                            $rootScope.showAlert($filter('translate')('error.print_failed_please_check_is_Acrobat_Reader_installed'), { level: 'warning', });
                            console.error(err);
                            _status = 2;
                        }
                        success(_status);
                    });
                });
            } else {
                var sumatraPDF = undefined;
                try{
                    sumatraPDF = window.nodeRequire('sumatra-pdf');
                }catch(e){}
                if(sumatraPDF){
                    var fs = window.nodeRequire('fs'), RuncardPath;
                    try{
                        RuncardPath = window.nodeRequire('electron').remote.app.getAppPath();
                    }catch(e){
                        RuncardPath = window.nodeRequire('path').dirname(process.execPath)+'\\package.nw';
                    }
                    RuncardPath += '\\www\\Runcard';
                    if(!fs.existsSync(RuncardPath)){
                        fs.mkdirSync(RuncardPath);
                    }
                    $rootScope.downloadFile(data.file_path, RuncardPath+'\\RuncardPreview'+timeInMs+'.pdf', function(dist_path){
                        //$rootScope.showLoading($filter('translate')('common.msg.pagerendered'));
                        $timeout(function(){
                            var _fn = sumatraPDF.printToDefault;
                            _fn({
                                path:RuncardPath+'\\RuncardPreview'+timeInMs+'.pdf',
                                settings:data.width > data.height ? 'landscape':'',
                                success:function(){
                                    //$rootScope.hideLoading();
                                    //$rootScope.showToast($filter('translate')('common.msg.success'));
                                    success(1);
                                },
                                error:function(error){
                                    //$rootScope.hideLoading();
                                    success(2);
                                }
                            });
                        });
                    });
                }
            }
        }
	}
]});
